import { useStore } from "../store";
// import { getLocalMainPath } from "../util/browser";
// import { isValidToken } from "../util/jwt";
import { request as baseRequest } from "../util/request";

export const api = (window as any).app.api || "";
export const jwtStorageKey = "userToken";

const headers: { [key: string]: any } = {
  Accept: "application/json",
  // 'Content-Type': 'application/json',
  "Content-Type": "application/x-www-form-urlencoded",
  mode: "cors", // no-cors, cors, *same-origin
};

const publicApis: string[] = [];

export function checkAuth(path: string): boolean {
  return publicApis.indexOf(path) === -1;
}

export function getJwtAuthHeader(path: string): { [key: string]: any } | void {
  const needAuth = checkAuth(path);

  if (needAuth) {
    const token = localStorage.getItem(jwtStorageKey);

    // if (!isValidToken(token)) {
    //   location.href = `${getLocalMainPath()}#/login`
    //   return
    // }

    headers.Authorization = `Bearer ${token}`;
  }

  return headers;
}
let store = null as any;
export function request(param: any): any {
  if (!store) store = useStore();
  const url = `${api}${param.url}`;
  param.header = getJwtAuthHeader(param.url);
  param.url = url;

  console.log("url", url);

  return baseRequest(param)
    ?.then((res: any) => {
      if (res.data.error != undefined) {
        return Promise.reject("服务端错误");
      }
      if (res.data.result.errcode != 0) {
        // store.commit("overlay/openModal", {
        //   type: "notify",
        //   infoType: "error",
        //   title: res.data.result.errmsg,
        // });
        alert(res.data.result.errmsg);
        return;
        // return Promise.reject(new Error(res.data.result.message))
      }

      console.log(res.data);
      return Promise.resolve(res.data.result);
    })
    .catch((err: any) => {
      console.log(err);
      return Promise.resolve(err);
    });
}
